package com.yunjing.elasticjob.service.impl;


import com.yunjing.elasticjob.entity.JobConfig;
import com.yunjing.elasticjob.service.JobDetailBuilder;
import com.yunjing.elasticjob.service.JobService;
import com.yunjing.elasticjob.service.TriggerBuilder;
import lombok.extern.slf4j.Slf4j;
import org.quartz.Job;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import org.springframework.stereotype.Service;


/**
 * @author zhiqi.shao
 * @Date 2018/6/14 9:57
 */
@Slf4j
@Service(value = "refreshJobService")
public class JobServiceImpl implements JobService {


    @Autowired
    private SchedulerFactoryBean schedulerFactoryBean;

    @Autowired
    private JobDetailBuilder jobDetailBuilder;

    @Autowired
    private TriggerBuilder triggerBuilder;


    @Override
    public boolean putJob(JobConfig jobConfig, Class<? extends Job> jobClass) {
        try {
            //创建新的定时任务
            schedulerFactoryBean.afterPropertiesSet();
            Scheduler scheduler = schedulerFactoryBean.getScheduler();
            scheduler.scheduleJob(jobDetailBuilder.build(jobConfig, jobClass), triggerBuilder.build(jobConfig));
            if (!scheduler.isShutdown()) {
                scheduler.start();
            }
            return true;
        } catch (SchedulerException e) {
            log.error("定时任务创建调度器异常", e);
        } catch (Exception e) {
            log.error("定时任务创建调度器异常", e);
        }
        return false;
    }
}


